package com.example.note;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.method.KeyListener;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;


import com.daquexian.flexiblerichtextview.FlexibleRichTextView;
import com.example.note.dao.NoteDAO;
import com.example.note.dao.NoteTagDAO;
import com.example.note.dbtool.MyDBHelper;
import com.example.note.imagedialog.base.Config;
import com.example.note.imagedialog.component.ShowImagesDialog;
import com.example.note.model.TNote;
import com.example.note.model.TNoteTag;
import com.example.note.util.GloableValue;
import com.example.note.util.ToastUtils;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class NoteActivity extends AppCompatActivity {

    private String ID;
    private EditText title;
    private EditText content;
    private KeyListener titleListener;
    private KeyListener contentListener;
    private NoteDAO taskNoteDAO;
    private Spinner spinner;
    private List<Object> tags;
    private FlexibleRichTextView richTextView;
    private LinearLayout pad ;
    String[] quicks = {"标题","颜色","居中","加粗","引用","下划线"};
    String[] maths = {"插入数学表达式",
            "累加","命令块","分式","sin","cos","tan",
            "极限","log","简单矩阵","复杂矩阵",
            "求积","积分","双重积分","三重积分",
            "闭合曲面曲线积分",
            "方程组",
            "存在","所有","空集","在集合中","子集","交","并",
            "开根号","右箭头","左箭头","数学表达式中文字"
    };
    String[] quicksItem = {"[h][/h]","[color=][/color]","[center][/center]","[b][/b]","[quote][/quote]","[u][/u]"};
    String[] mathItem = {"$$$$",
            "\\sum_{i=0}^{n}","{}","\\frac{}{}","\\sin\\theta","\\cos\\theta","\\tan\\theta",
            "\\lim_{\\Delta x\\to 0}","\\log_\\alpha X","\\begin{vmatrix}\n"+"x & y \\\\\n" + "z & v\n" + "\\end{vmatrix}",
            "\\begin{bmatrix}\n" + "0      & \\cdots & 0      \\\\\n" + "\\vdots & \\ddots & \\vdots \\\\\n" + "0      & \\cdots & 0\n" + "\\end{bmatrix}",
            "\\prod_{i=1}^N x_i","\\int_{-N}^{N} e^x\\, dx","\\iint_{D}^{W} \\, dx\\,dy","\\iiint_{E}^{V} \\, dx\\,dy\\,dz",
            "\\oint_{C} x^3\\, dx + 4y^2\\, dy",
            "\\begin{cases}\n" + "3x + 5y +  z \\\\\n" + "7x - 2y + 4z \\\\\n" + "-6x + 3y + 2z\n" + "\\end{cases}",
            "\\exists","\\forall","\\empty","\\in","\\subset","\\bigcap","\\bigcup",
            "\\sqrt[n]{3}","\\rightarrow","\\leftarrow",""

    };
    private LinearLayout container;
    private LinearLayout mathContainer;
    private OnSwitch switchListener;

    private void bindHZWData(){
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        layoutParams.gravity = Gravity.CENTER;
        layoutParams.setMargins(20,10,20,10);
        //插入编辑
        TextView T0 = new TextView(this);
        T0.setText("编辑");
        T0.setLayoutParams(layoutParams);
        T0.setOnClickListener(new Onclick());
        container.addView(T0);
        container.invalidate();
        //插入切换渲染
        TextView T1 = new TextView(this);
        T1.setText("切换（渲染）");
        T1.setLayoutParams(layoutParams);
        switchListener = new OnSwitch();
        T1.setOnClickListener(switchListener);
        container.addView(T1);
        container.invalidate();

        for(int i =0;i<quicks.length;i++){
            TextView textView = new TextView(this);
            textView.setText(quicks[i]);
            textView.setLayoutParams(layoutParams);
            textView.setTextSize(15);
            textView.setOnClickListener(new OnClickInsert(quicksItem[i]));
            container.addView(textView);
            container.invalidate();
        }

        for(int i =0;i<maths.length;i++){
            TextView textView = new TextView(this);
            textView.setText(maths[i]);
            textView.setLayoutParams(layoutParams);
            textView.setTextSize(15);
            textView.setOnClickListener(new OnClickInsert(mathItem[i]));
            mathContainer.addView(textView);
            mathContainer.invalidate();
        }
    }


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_note);

        title = findViewById(R.id.title);
        content = findViewById(R.id.content);
        titleListener =  title.getKeyListener();
        contentListener = content.getKeyListener();
        title.setKeyListener(null);
        content.setKeyListener(null);
        spinner = findViewById(R.id.spinner);
        container =(LinearLayout)findViewById(R.id.horizontalScrollViewItemContainer);
        mathContainer = findViewById(R.id.MathScrollViewItemContainer);
        pad = findViewById(R.id.pad);

        bindHZWData();

        // 建立数据源
        String[] mItems = {"1","2","3","4"};
        NoteTagDAO noteTagDAO = (NoteTagDAO) new MyDBHelper(this).getDAO(NoteTagDAO.class);
        tags = noteTagDAO.queryAll();
        mItems=new String[tags.size()];
        for (int i =0;i<tags.size();i++){
            TNoteTag tTaskNoteTag = (TNoteTag) tags.get(i);
            mItems[i] = tTaskNoteTag.noteTag;
        }
        // 建立Adapter并且绑定数据源
        ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, mItems);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner .setAdapter(adapter);


        Intent intent = getIntent();
        ID = intent.getStringExtra("noteID");

        taskNoteDAO = (NoteDAO) new MyDBHelper(this).getDAO(NoteDAO.class);
        List<Object> tmp =taskNoteDAO.queryByID(ID);
        final TNote tTaskNote = (TNote) tmp.get(0);
        title.setText(tTaskNote.title);
        Date date = new Date(Long.parseLong(tTaskNote.recordDate));

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日");
        TextView textView = findViewById(R.id.time);
        textView.setText(simpleDateFormat.format(date));
        content.setText(tTaskNote.content);

        for (int i =0;i<tags.size();i++){
            TNoteTag tTaskNoteTag = (TNoteTag) tags.get(i);
            if (tTaskNote.noteTagID.equals(tTaskNoteTag.ID)){
                spinner.setSelection(i);
            }
        }
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                TNoteTag tTaskNoteTag = (TNoteTag) tags.get(i);
                taskNoteDAO.updateNoteTagIDByID(tTaskNote.ID,tTaskNoteTag.ID);
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });

        richTextView = (FlexibleRichTextView) findViewById(R.id.test_text);
        richTextView.setImageListener(new FlexibleRichTextView.OnClickImageListener() {

            @Override
            public void onclick(View view, String url) {
                //Toast.makeText(view.getContext(),"image is long click on note! "+url,Toast.LENGTH_SHORT).show();
                getDeviceDensity();
                final List<String> urls = new ArrayList<>();
                urls.add(url);
                new ShowImagesDialog(NoteActivity.this, urls).show();
            }
        });
        //初始化移动到application
        richTextView.setVisibility(View.GONE);//默认为消失不见
    }

    /**
     * 获取当前设备的屏幕密度等基本参数
     */
    protected void getDeviceDensity() {
        DisplayMetrics metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);
        Config.EXACT_SCREEN_HEIGHT = metrics.heightPixels;
        Config.EXACT_SCREEN_WIDTH = metrics.widthPixels;
    }

    @Override
    protected void onResume() {
        super.onResume();
        if(GloableValue.tmpString.length()!=0){
            new AlertDialog.Builder(this).setTitle("结构化思考有遗留内容，是否加入？")
                    .setMessage("提示")
                    .setPositiveButton("是", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            StringBuffer stringBuffer = new StringBuffer();
                            stringBuffer.append(content.getText()+"\n");
                            stringBuffer.append(GloableValue.tmpString);
                            GloableValue.tmpString="";
                            content.setText(stringBuffer.toString());
                        }
                    })
                    .setNegativeButton("否", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            GloableValue.tmpString="";
                        }
                    }).show();
        }
    }

    private class OnSwitch implements View.OnClickListener{
        private String RENDER = "RENDER";
        private String EDIT = "EDIT";
        private String mode = EDIT;
        private TextView currentView;
        @Override
        public void onClick(View view) {
            try {
                TextView button = (TextView) view;
                currentView = button;
                if (mode.equals("EDIT")) {
                    richTextView.setText(content.getText().toString());
                    mode = RENDER;
                    content.setVisibility(View.GONE);
                    richTextView.setVisibility(View.VISIBLE);
                    button.setText("切换（编辑）");
                } else {
                    mode = EDIT;
                    content.setVisibility(View.VISIBLE);
                    richTextView.setVisibility(View.GONE);
                    button.setText("切换（渲染）");
                }
            }catch (Exception e){
                ToastUtils.show(NoteActivity.this,e.getMessage(), Toast.LENGTH_LONG);
            }
        }

        public void onSwitch(){
            if (currentView==null){
                return;
            }
            mode = EDIT;
            content.setVisibility(View.VISIBLE);
            richTextView.setVisibility(View.GONE);
            currentView.setText("切换（渲染）");
        }
    }

    private class OnClickInsert implements  View.OnClickListener{

        private String insertContent;

        public OnClickInsert(String insertContent) {
            this.insertContent = insertContent;
        }

        @Override
        public void onClick(View v) {
            int index = content.getSelectionStart();
            Editable editable = content.getText();
            editable.insert(index, insertContent);
        }
    }

    private class Onclick implements View.OnClickListener{
        private boolean mode = true;
        @Override
        public void onClick(View view) {
            TextView self = (TextView) view;
            try {
                if (mode) {
                    mode = false;
                    title.setKeyListener(titleListener);
                    content.setKeyListener(contentListener);
                    self.setText("保存");
                    switchListener.onSwitch();
                } else {
                    mode = true;
                    title.setKeyListener(null);
                    content.setKeyListener(null);
                    self.setText("编辑");
                    taskNoteDAO.updateContentByID(ID, content.getText().toString());
                    taskNoteDAO.updateTitleByID(ID, title.getText().toString());
                }
            }catch (Exception e){
                AlertDialog.Builder builder = new AlertDialog.Builder(NoteActivity.this);
                builder.setTitle("提示");
                builder.setMessage(e.toString());
                builder.show();
            }
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_note, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        int id = item.getItemId();

        if(id==R.id.action_pad){
            pad.setVisibility(View.VISIBLE);
        }

        if (id==R.id.action_full){
            pad.setVisibility(View.GONE);
        }

        return super.onOptionsItemSelected(item);
    }


}
